import { _codeParse, _getUserInfo } from "./sub";
import { util, ParamErr } from "utils";
import { dbHandle } from "./sub/dbHandle";
import type { AliToken, AliUserInfo } from "./aliLoginService.type";

// 阿里登录
async function aliLoginAction(param: any) {
    let { code } = param || {};
    if (util.emptyValue(code)) {
        return util.resErr(new ParamErr("code"));
    }
    // token的数据
    let [parseErr, parseData] = await _codeParse(code);
    if (!util.nilValue(parseErr)) {
        return util.resErr(parseErr!);
    }
    let tokenData = parseData as AliToken;
    // 获取用户数据
    let [userErr, userData] = await _getUserInfo(tokenData.access_token);
    if (!util.nilValue(userErr)) {
        return util.resErr(userErr!);
    }
    let userInfo = userData as AliUserInfo;

    // 数据库操作
    let [dbErr, dbData] = await dbHandle(tokenData, userInfo);
    if (!util.nilValue(dbErr)) {
        return util.resErr(dbErr!);
    }
    return util.resData(dbData);
}

export { aliLoginAction };
